import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { RoleAccessEntity } from 'src/entity/role_access.entity';
import { RoleAccessReqDto } from 'src/modules/background/role-access/dto/role.access.req.dto';
import { RoleAccessVo } from 'src/modules/background/role-access/vo/role.access.res';
import { Repository } from 'typeorm';

@Injectable()
export class RoleAccessService {
    constructor(
        @InjectRepository(RoleAccessEntity)
        private readonly roleAccessRepository: Repository<RoleAccessEntity>,
    ) { }
    // 给当前角色ID授权菜单、接口权限
    async roleToAccess(roleId: number, roleAccessReqDto: RoleAccessReqDto): Promise<string> {
        try {
            const { access } = roleAccessReqDto;
            // 先清空所有关联
            await this.roleAccessRepository.delete({ roleId })
            const newAccess = access.map(item => {
                return {
                    roleId,
                    accessId: item
                }
            })
            const result = this.roleAccessRepository.create(newAccess)
            await this.roleAccessRepository.save(result)
            return '分配成功';
        } catch (error) {
            throw new HttpException(error, HttpStatus.OK);
        }
    }
    async accessListByRoleId(roleId: number): Promise<RoleAccessVo[]> {
        const result = this.roleAccessRepository.find({
            where: { roleId },
            select: ['id', 'accessId'],
        })
        return result
    }
}
